<template>
  <div class="wrapper">
    <!-- 搜索栏 -->
    <el-form v-show="showSearch" :inline="true" :model="searchForm" class="search-container" label-width="80px">
      <el-form-item label="收藏夹名">
        <el-input v-model="searchForm.title" placeholder="请输入收藏夹名" clearable></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchForm.public" placeholder="请选择收藏夹状态" clearable>
          <el-option label="公开" :value="true"></el-option>
          <el-option label="私有" :value="false"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="getTableList()" type="primary" round icon="el-icon-search">查询</el-button>
        <el-button @click="resetSearch()" round icon="el-icon-refresh-right">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 操作区 -->
    <el-row :gutter="10" class="operation-row">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="createCollectionDialog()"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="selectedData.length === 0"
          @click="batchDelete()"
        >批量删除</el-button>
      </el-col>
      <table-toolbar :showSearch.sync="showSearch" @queryTable="getTableList" :columns="columns"></table-toolbar>
    </el-row>
    <el-table
      :data="tableList"
      border
      v-loading="tableListLoading"
      @selection-change="handleSelectionChange"
      style="width:100%;"
    >
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column
        prop="title"
        label="收藏夹名"
        header-align="center"
        align="center"
        width="150"
        v-if="columns[0].visible">
      </el-table-column>
      <el-table-column
        prop="description"
        label="描述"
        header-align="center"
        align="center"
        width="300"
        v-if="columns[1].visible"
        show-overflow-tooltip>
        <template slot-scope="scope">
          <div class="desc-short">{{scope.row.description}}</div>
        </template>
      </el-table-column>
      <el-table-column
        prop="public"
        label="状态"
        header-align="center"
        align="center"
        width="150"
        v-if="columns[2].visible">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.public">公开</el-tag>
          <el-tag type="warning" v-else>私有</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="createdAt"
        label="创建时间"
        header-align="center"
        align="center"
        v-if="columns[3].visible">
      </el-table-column>
      <el-table-column
        prop="updatedAt"
        label="修改时间"
        header-align="center"
        align="center"
        v-if="columns[4].visible">
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        header-align="center"
        align="center"
        width="300">
        <template slot-scope="scope">
          <el-button plain icon="el-icon-view" size="mini" @click="viewCollectionDialog(scope.row.id)">查看</el-button>
          <el-button plain icon="el-icon-edit" size="mini" @click="editCollectionDialog(scope.row)">编辑</el-button>
          <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="deleteCollection(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getTableList" />
    <!-- 用户新建、编辑 -->
    <el-dialog :title="textMap[dialogType]" :visible.sync="dialogVisible" width="40%">
      <el-form ref="collectionForm" :rules="rules" :model="collectionForm" label-position="right" label-width="90px">
        <el-form-item label="收藏夹名" prop="title">
          <el-input clearable v-model="collectionForm.title" placeholder="收藏夹名" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input clearable v-model="collectionForm.description" placeholder="收藏夹描述" />
        </el-form-item>
        <el-form-item label="作者" prop="owner_id">
          <el-row>
            <el-col :span="18">
              <el-input clearable @clear="resetSearchUser" v-model="collectionForm.owner_id" placeholder="收藏夹作者id" />
            </el-col>
            <el-col :offset="1" :span="5">
              <el-button type="primary" @click="searchOwner">搜索</el-button>
            </el-col>
          </el-row>
          <div v-if="Object.keys(searchResult).length > 0" class="search-wrapper">
            <el-radio v-model="collectionForm.owner_id" :label="collectionForm.owner_id"></el-radio>
            <img :src="searchResult.avatar" class="search-avatar" />
            <div class="search-name">{{ searchResult.username }}</div>
            <div class="search-type">
              <el-tag type="info" v-if="searchResult.type === 'user'">普通用户</el-tag>
              <el-tag type="success" v-if="searchResult.type === 'admin'">管理员</el-tag>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="public">
          <el-select v-model="collectionForm.is_public" placeholder="状态">
            <el-option v-for="item in statusOptions" :key="item.id" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogType === 'create' ? createCollection() : editCollection()">
          提交
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="收藏夹内容" :visible.sync="collectionVisible" width="60%">
      <el-table
        :data="articleList"
        border
        v-loading="articleListLoading"
        style="width:100%;"
      >
        <el-table-column type="expand">
          <template slot-scope="props">
            {{ props.row.content }}
          </template>
        </el-table-column>
        <el-table-column
          prop="title"
          label="文章名"
          header-align="center"
          align="center"
          width="150">
        </el-table-column>
        <el-table-column
        prop="user"
        label="作者"
        header-align="center"
        align="center"
        width="150">
        <template slot-scope="scope">
          <el-popover
            placement="right"
            title=""
            trigger="click">
            <img :src="scope.row.user.avatar" style="width:150px" />
            <img slot="reference" :src="scope.row.user.avatar" class="avatar">
          </el-popover>
          <div class="author">{{ scope.row.user.username }}</div>
        </template>
      </el-table-column>
      <el-table-column
        prop="picture"
        label="文章大图"
        header-align="center"
        align="center"
        width="150">
        <template slot-scope="scope">
          <el-popover
            placement="right"
            title=""
            trigger="click">
            <img :src="scope.row.picture" style="width:500px">
            <img slot="reference" :src="scope.row.picture" class="bg-img">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        label="审核状态"
        header-align="center"
        align="center"
        width="150">
        <template slot-scope="scope">
          <el-tag type="info" v-if="scope.row.status === '1'">待审核</el-tag>
          <el-tag v-if="scope.row.status === '2'">审核中</el-tag>
          <el-tag type="success" v-if="scope.row.status === '3'">审核通过</el-tag>
          <el-tag type="danger" v-if="scope.row.status === '4'">审核不过</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="view"
        label="浏览量"
        header-align="center"
        align="center"
        width="150">
      </el-table-column>
      <el-table-column
        prop="like"
        label="点赞数"
        header-align="center"
        align="center"
        width="150">
      </el-table-column>
      <el-table-column
        prop="createdAt"
        label="创建日期"
        header-align="center"
        align="center"
        width="150">
      </el-table-column>
      <el-table-column
        prop="updatedAt"
        label="更新日期"
        header-align="center"
        align="center"
        width="150">
      </el-table-column>
      </el-table>
      <pagination v-show="articleTotal>0" :total="articleTotal" :page.sync="articleListQuery.page" :limit.sync="articleListQuery.limit" @pagination="getCollectionArticles" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="collectionVisible = false">
          关闭
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCollectionsB, createCollectionB, editCollectionB, deleteCollectionB, batchDeleteCollectionsB, getCollectionArticlesB } from '@/api/admin'
import { getUserIdInfo } from '@/api/user'
export default {
  data() {
    return {
      searchForm: {
        title: undefined,
        public: undefined
      },
      tableList: [],
      tableListLoading: false,
      //选择的数据
      selectedData: [],
      //分页参数
      listQuery: {
        page: 1,
        limit: 20,
        sort: '+id'
      },
      //总数
      total: 0,
      // 显示搜索条件
      showSearch: true,
      // 列信息
      columns: [
        { key: 0, label: `收藏夹名`, visible: true },
        { key: 1, label: `描述`, visible: true },
        { key: 2, label: `状态`, visible: true },
        { key: 3, label: `创建时间`, visible: true },
        { key: 4, label: `修改时间`, visible: true }
      ],
      //dialog
      dialogVisible: false,
      //dialog标题
      textMap: {
        edit: '编辑收藏夹',
        create: '新建收藏夹'
      },
      //dialog类型
      dialogType: '',
      collectionForm: {
        id: '',
        title: '',
        description: '',
        owner_id: '',
        is_public: true
      },
      //表单验证
      rules: {
        title: [{ required: true, message: '收藏夹名为必填项', trigger: 'blur' }],
        description: [{ required: true, message: '描述为必填项', trigger: 'blur' }],
        owner_id: [{ required: true, message: '作者id为必填项', trigger: 'blur' }],
        public: [{ required: true, message: '状态为必填项', trigger: 'blur' }]
      },
      statusOptions: [
        { name: '公开', value: true },
        { name: '私有', value: false }
      ],
      searchResult: {},
      // 收藏夹内容dialog
      collectionVisible: false,
      // 收藏夹内容文章列表
      articleList: [],
      articleTotal: 0,
      articleListLoading: false,
      articleListQuery: {
        page: 1,
        limit: 20
      },
    }
  },
  filters: {
    convertTime: function(val) {
      return new Date(val).toLocaleDateString()
    }
  },
  created() {
    this.getTableList()
  },
  methods: {
    convertTime(val) {
      return new Date(val).toLocaleDateString()
    },
    //获取表单数据
    getTableList() {
      this.tableListLoading = true
      let data = {
        searchForm: this.searchForm,
        page: this.listQuery.page,
        limit: this.listQuery.limit
      }
      getCollectionsB(data).then(res => {
        if(res.data.code === '0') {
          // this.$message.success(res.data.desc)
          this.tableList = res.data.collections.rows
          this.total = res.data.collections.count
          this.tableList.forEach(item => {
            item.createdAt = this.convertTime(item.createdAt)
            item.updatedAt = this.convertTime(item.updatedAt)
          })
        } else {
          this.$message.error(res.data.desc)
        }
        this.tableListLoading = false
      }).catch(err => {
        this.$message.error(res.data.desc)
        this.tableListLoading = false
      })
    },
    //数据多选
    handleSelectionChange(val) {
      this.selectedData = val
    },
    //重置搜索表单
    resetSearch() {
      this.searchForm = {
        title: undefined,
        public: undefined,
      }
      this.getTableList()
    },
    //重置弹窗表单
    resetForm() {
      this.collectionForm = {
        title: '',
        description: '',
        owner_id: '',
        is_public: true
      }
    },
    //关闭dialog
    closeForm() {
      this.$refs.collectionForm.resetFields()
      this.dialogVisible = false
    },
    //新增收藏
    createCollectionDialog() {
      this.dialogType = 'create'
      this.dialogVisible = true
      this.searchResult = {}
      this.resetForm()
    },
    createCollection() {
      createCollectionB(this.collectionForm).then(res => {
        if(res.data.code === '0') {
          this.$message.success(res.data.desc)
          this.getTableList()
        } else {
          this.$message.error(res.data.desc)
        }
        this.closeForm()
      }).catch(err => {
        this.$message.error(err)
        this.closeForm()
      })
    },
    //修改收藏
    editCollectionDialog(row) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.searchResult = {}
      this.resetForm()
      this.collectionForm.id = row.id
      this.collectionForm.title = row.title
      this.collectionForm.description = row.description
      this.collectionForm.owner_id = row.owner_id
      this.searchOwner()
    },
    editCollection() {
      editCollectionB(this.collectionForm).then(res => {
        if(res.data.code === '0') {
          this.$message.success(res.data.desc)
          this.getTableList()
        } else {
          this.$message.error(res.data.desc)
        }
        this.closeForm()
      }).catch(err => {
        this.$message.error(res.data.desc)
        this.closeForm()
      })
    },
    //删除收藏
    deleteCollection(row) {
      this.$confirm('此操作将永久删除收藏夹'+`[${row.title}]`+', 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let data = {
            id: row.id
          }
          deleteCollectionB(data).then(res => {
            if(res.data.code === '0') {
              this.$message.success(res.data.desc)
              this.getTableList()
            } else {
              this.$message.error(res.data.desc)
            }
          }).catch(err => {
            this.$message.error(res.data.desc)
          })
        }).catch(err => {
          console.log(err)
        })
    },
    //批量删除收藏
    batchDelete() {
      this.$confirm('此操作将永久删除选择的收藏夹, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let ids = []
          this.selectedData.forEach(item => {
            ids.push(item.id)
          })
          let data = {
            ids: ids
          }
          batchDeleteCollectionsB(data).then(res => {
            if(res.data.code === '0') {
              this.$message.success(res.data.desc)
              this.getTableList()
            } else {
              this.$message.error(res.data.desc)
            }
          }).catch(err => {
            this.$message.error(res.data.desc)
          })
        }).catch(err => {
          console.log(err)
        })
    },
    // 根据用户名搜素用户
    searchOwner() {
      if(!this.collectionForm.owner_id) {
        this.$message.error('请先输入用户id')
      } else {
        getUserIdInfo({ id: this.collectionForm.owner_id }).then(res => {
          if(res.data.code == '0') {
            this.searchResult = res.data.userInfo
          }
        }).catch(err => {
          console.log(err)
        })
      }
    },
    // 重置用户搜索结果
    resetSearchUser() {
      this.searchResult = {}
    },
    // 查看收藏夹内容
    viewCollectionDialog(id) {
      this.collectionVisible = true
      this.getCollectionArticles(id)
    },
    // 根据收藏夹搜索文章
    getCollectionArticles(id) {
      this.articleListLoading = true
      let data = {
        collection_id: id,
        page: this.articleListQuery.page,
        limit: this.articleListQuery.limit
      }
      getCollectionArticlesB(data).then(res => {
        if(res.data.code == '0') {
          this.articleList = res.data.articles.rows
          this.articleTotal = res.data.articles.count
          this.articleList.forEach(item => {
            item.createdAt = this.convertTime(item.createdAt)
            item.updatedAt = this.convertTime(item.updatedAt)
          })
        }
        this.articleListLoading = false
      }).catch(err => {
        this.articleListLoading = false
        console.log(err)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.wrapper {
  margin: 10px;
  color: #999;
}
.operation-row {
  margin-bottom: 25px;
}
.desc-short {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: center;
}
.search-wrapper {
  display: flex;
  align-items: center;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 6px 12px;
  margin-top: 10px;
  .search-avatar {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    margin-right: 6px;
  }
  .search-name {
    color: #666;
    margin-right: 6px;
    width: 100px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
.avatar {
  width: 45px;
  height: 45px;
  border-radius: 4px;
  cursor: pointer;
}
</style>